package com.iqiyi.pps.epg.web.timer;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.core.model.sginal.Server;
import com.iqiyi.pps.epg.core.model.sginal.ServerStatus;
import com.iqiyi.pps.epg.core.service.sginal.ServerService;
import com.iqiyi.pps.epg.core.service.sginal.ServerStatusService;
import com.iqiyi.pps.epg.core.utils.ApiSginalServerStatusUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by zhang on 2017/08/28.
 */
public class AutoSginalServerStatusTrigger {
    private static Logger logger = LoggerFactory.getLogger(AutoSginalServerStatusTrigger.class);

    @Autowired
    private ServerService serverService;

    @Autowired
    private ServerStatusService serverStatusService;

    public void task() {
        logger.info("[AutoSginalServerStatusTrigger][start]");
        try {
            List<Server> serverList = serverService.getAll();
            for (Server server : serverList) {
                JSONArray jsonArray = ApiSginalServerStatusUtil.getLoad(server.getInsideServerIp());
                if (jsonArray != null&&jsonArray.size()>0) {
                    //遍历metrics  for
                    ServerStatus serverStatus = new ServerStatus();
                    serverStatus.setServerId(server.getId());
                    for(Object obj : jsonArray){
                        JSONObject jobj = (JSONObject)obj;
                        JSONObject jtag = jobj.getJSONObject("tags");
                        String val = jobj.getString("value");
                        String metric = jobj.getString("metric");

                        if(metric.equals(ServerStatus.STATUS_LOAD)){
                            serverStatus.setLoadValue(val);
                            server.setLoad(Double.parseDouble(val));
                        }

                        if(metric.equals(ServerStatus.STATUS_DISK)){
                            String tagA = jtag.getString("a");
                            String tagB = jtag.getString("b");
                            if(tagA.equals("/")){
                                if(tagB.equals("free")){
                                    serverStatus.setAllFree(val);
                                }
                                if(tagB.equals("used")){
                                    serverStatus.setAllUsed(val);
                                }
                            }
                            if(tagA.equals("/data")){
                                if(tagB.equals("free")){
                                    serverStatus.setDataFree(val);
                                }
                                if(tagB.equals("used")){
                                    serverStatus.setDataUsed(val);
                                }
                            }
                        }

                        if(metric.equals(ServerStatus.STATUS_MEM)){
                            String tagA = jtag.getString("a");
                            if(tagA.equals("available")){
                                serverStatus.setAvailableMem(val);
                            }
                            if(tagA.equals("empty_bracket")){
                                serverStatus.setAllMem(val);
                            }
                        }

                        if(metric.equals(ServerStatus.STATUS_SWAP)){
                            String tagB = jtag.getString("b");
                            if(tagB.equals("pfree")){
                                float per = Float.parseFloat(val);
                                serverStatus.setFreeSwapPer(Math.round(per)+"");
                            }
                        }

                        if(metric.equals(ServerStatus.STATUS_ICMPLOSS)){
                            serverStatus.setInIcmploss(val);
                        }
                    }
                    String outIp = server.getOutsideServerIp();
                    if(outIp!=null&&!outIp.equals("")){
                        JSONArray jsonOutArray = ApiSginalServerStatusUtil.getoutLoad(outIp);
                        if(jsonArray != null&&jsonOutArray.size()>0){
                            JSONObject outLoss = (JSONObject)jsonOutArray.get(0);
                            serverStatus.setOutIcmploss(outLoss.getString("value"));
                        }
                    }

                    String dataFreePer = getPer2(serverStatus.getDataFree(),serverStatus.getDataUsed()); //errorInd=1
                    String allFreePer = getPer2(serverStatus.getAllFree(),serverStatus.getAllUsed()); //errorInd=2
                    String availableMemPer = getPer1(serverStatus.getAvailableMem(),serverStatus.getAllMem()); //errorInd=3
                    String freeSwapPer = getPer1(serverStatus.getFreeSwapPer(),"100"); //errorInd=4

                    serverStatus.setDataFreePer(dataFreePer);
                    serverStatus.setAvailableMemPer(availableMemPer);
                    serverStatus.setAllFreePer(allFreePer);
                    int count=-1,errorInd=-2;

                    if(serverStatus.getInIcmploss()!=null&&serverStatus.getInIcmploss().equals("0")){
                        count=0;
                        if(dataFreePer!=null&&Server.ERROR_Threshold.compareTo(dataFreePer)==1){
                            count++;errorInd=1;
                        }

                        if(allFreePer!=null&&Server.ERROR_Threshold.compareTo(allFreePer)==1){
                            count++;errorInd=2;
                        }

                        if(availableMemPer!=null&&Server.ERROR_Threshold.compareTo(availableMemPer)==1){
                            count++;errorInd=3;
                        }
                        if(freeSwapPer!=null&&Server.ERROR_Threshold.compareTo(freeSwapPer)==1){
                            count++;errorInd=4;
                        }
                        if(count==0){
                            errorInd = 0;
                        }
                        if(count>1){
                            errorInd = -1;
                        }
                    }

                    server.setDataFreePer(dataFreePer);
                    server.setAvailableMemPer(availableMemPer);
                    server.setAllFreePer(allFreePer);
                    server.setFreeSwapPer(freeSwapPer);
                    server.setOutIcmploss(serverStatus.getOutIcmploss());
                    server.setInIcmploss(serverStatus.getInIcmploss());
                    server.setMonitor(errorInd);

                    serverStatusService.add(serverStatus);
                    serverService.update(server);
                }
            }

        } catch(Exception e) {
            logger.error("[AutoSginalServerStatusTrigger][error]", e);
        } finally {
            logger.info("[AutoSginalServerStatusTrigger][end]");
        }
    }

    public static String getPer1(String free,String total){
        if(free!=null&&total!=null){
            float a = Float.parseFloat(free);
            float b = Float.parseFloat(total);
            int per = Math.round(a/b*100);
            if(per<100){
                return "0"+per;
            }else{
                return per+"";
            }
        }
        return null;
    }

    public static String getPer2(String free,String used){
        if(free!=null&&used!=null){
            float a = Float.parseFloat(free);
            float b = Float.parseFloat(used);
            int per = Math.round(a/(a+b)*100);
            if(per<100){
                return "0"+per;
            }else{
                return per+"";
            }
        }
        return null;
    }

}
